Replace string as camelCase in MSSQL

SQL Code with Explanations

SQL Code with Explanations


DROP TABLE IF EXISTS #YourTableName;
CREATE TABLE #YourTableName (yourColumn VARCHAR(20));
INSERT INTO #YourTableName VALUES ('abcd_abcd_abcd'), ('dfredsdfsf');

;WITH CTE AS 
(
    SELECT 
        ISNULL(STUFF(yourColumn, CHARINDEX('_', yourColumn), 2, UPPER(SUBSTRING(yourColumn, CHARINDEX('_', yourColumn) + 1, 1))), yourColumn) AS yourColumn,
        CHARINDEX('_', yourColumn) AS b,
        0 AS num
    FROM 
        #YourTableName a
    UNION ALL
    SELECT 
        STUFF(yourColumn, CHARINDEX('_', yourColumn), 2, UPPER(SUBSTRING(yourColumn, CHARINDEX('_', yourColumn) + 1, 1))) AS a,
        CHARINDEX('_', yourColumn) AS b,
        num + 1 AS num
    FROM 
        CTE a
    WHERE    
        b > 0
)
SELECT 
    * 
FROM 
    CTE
WHERE 
    yourColumn IS NOT NULL
    AND CHARINDEX('_', yourColumn) = 0;

Explanation:

DROP TABLE IF EXISTS #YourTableName;
This command deletes the table named #YourTableName if it exists. It ensures that the table is removed before creating a new one.

CREATE TABLE #YourTableName (yourColumn VARCHAR(20));
This command creates a new table named #YourTableName with a single column yourColumn of type VARCHAR(20).

INSERT INTO #YourTableName VALUES ('abcd_abcd_abcd'), ('dfredsdfsf');
This command inserts two rows into the table #YourTableName with sample data.

;WITH CTE AS ( ... )
This section defines a Common Table Expression (CTE) named CTE. The CTE performs a recursive operation to process the yourColumn values by replacing underscores with a capitalized letter following the underscore.

SELECT ISNULL(STUFF(yourColumn, CHARINDEX('_', yourColumn), 2, UPPER(SUBSTRING(yourColumn, CHARINDEX('_', yourColumn) + 1, 1))), yourColumn) AS yourColumn, ...
This SELECT statement within the CTE performs the following operations:

  • ISNULL(..., yourColumn): Replaces the underscore and the following character with its uppercase version.
  • CHARINDEX('_', yourColumn): Finds the position of the first underscore.
  • STUFF(...): Replaces parts of the string based on the position of the underscore.

UNION ALL
Combines the results of the initial CTE query with the recursive query. The recursive part continues to process the string until no underscores are left.

SELECT * FROM CTE WHERE yourColumn IS NOT NULL AND CHARINDEX('_', yourColumn) = 0;
This final SELECT statement retrieves the results from the CTE where yourColumn does not contain any underscores (i.e., processing is complete).

Login for comment